import CONFIG from './apiConfig.js'
import md5 from './md5.js'

const API = {};

// 签名算法工具类
class SignatureUtils {
	// 生成时间戳
	static generateTimestamp() {
		return Math.floor(Date.now() / 1000).toString();
	}

	// 获取用户授权token
	static getAuthorization() {
		const userInfo = uni.getStorageSync('user_info');
		return userInfo && userInfo.token ? `Bearer ${userInfo.token}` : '';
	}

	// 获取租户ID
	static getTenantId() {
		return CONFIG.tenantId;
	}

	// 获取密钥
	static getSecretKey() {
		return CONFIG.secretKey;
	}

	// 对GET参数按ASCII升序排序
	static sortParams(params) {
		if (!params || Object.keys(params).length === 0) {
			return '';
		}
		
		const sortedKeys = Object.keys(params).sort();
		return sortedKeys.map(key => `${key}=${params[key]}`).join('&');
	}

	// 生成第一次签名
	static generateFirstSignature(url, timestamp, queryParams, bodyContent, secretKey) {
		const queryString = this.sortParams(queryParams);
		const bodyString = bodyContent || '';
		
		// 按顺序拼接：url → timespan → 查询参数 → body → 密钥
		// 构建签名字符串，空变量不拼接&
		let signParts = [url, timestamp];
		
		if (queryString) {
			signParts.push(queryString);
		}
		
		if (bodyString) {
			signParts.push(bodyString);
		}
		
		signParts.push(`key=${secretKey}`);
		
		const signString = signParts.join('&');
		
		console.log('第一次签名字符串:', signString);
		return md5(signString);
	}

	// 生成最终签名
	static generateFinalSignature(tenantId, firstSign, timestamp, authorization) {
		const signString = `${tenantId}${firstSign}${timestamp}${authorization}`;
		
		console.log('最终签名字符串:', signString);
		return md5(signString);
	}

	
}

// 主要的API请求方法
API.request = (route, params = {}, method = 'POST', options = {}) => {
	const timestamp = SignatureUtils.generateTimestamp();
	const authorization = SignatureUtils.getAuthorization();
	const tenantId = SignatureUtils.getTenantId();
	const secretKey = SignatureUtils.getSecretKey();

	// 处理请求参数
	let queryParams = {};
	let bodyContent = '';
	let requestUrl = CONFIG.host + route;

	if (method.toUpperCase() === 'GET') {
		// GET请求参数放在URL中
		queryParams = params;
		const queryString = SignatureUtils.sortParams(queryParams);
		if (queryString) {
			requestUrl += (route.includes('?') ? '&' : '?') + queryString;
		}
	} else {
		// POST/PUT等请求参数放在body中
		// 确保body内容与签名时完全一致
		if (options.contentType === 'application/x-www-form-urlencoded') {
			// 表单提交格式
			bodyContent = SignatureUtils.sortParams(params);
		} else {
			// JSON格式
			bodyContent = JSON.stringify(params);
		}
	}

	// 生成第一次签名
	// 使用路由路径（不包含域名）进行签名
	const firstSign = SignatureUtils.generateFirstSignature(
		route, // 使用路由路径，不包含域名
		timestamp,
		queryParams,
		bodyContent,
		secretKey
	);

	// 生成最终签名
	const finalSign = SignatureUtils.generateFinalSignature(
		tenantId,
		firstSign,
		timestamp,
		authorization
	);

	// 将签名参数添加到URL上
	const signatureParams = {
		timespan: timestamp,
		sign: finalSign,
		tenantId: tenantId
	};
	
	// 构建签名参数字符串
	const signatureQueryString = SignatureUtils.sortParams(signatureParams);
	if (signatureQueryString) {
		requestUrl += (requestUrl.includes('?') ? '&' : '?') + signatureQueryString;
	}

	// 构建请求头
	const header = {
		...options.header
	};

	// 设置Content-Type
	if (options.contentType) {
		header['Content-Type'] = options.contentType;
	} else if (method.toUpperCase() !== 'GET') {
		header['Content-Type'] = 'application/json';
	}

	// 如果有授权token，添加到请求头
	// if (authorization) {
	// 	header['Authorization'] = authorization;
	// }
	header['Authorization'] = authorization;	
	console.log('请求信息:', {
		route,
		url: requestUrl,
		method,
		header,
		queryParams,
		bodyContent,
		timestamp,
		firstSign,
		finalSign,
		signatureParams
	});

	return new Promise((resolve, reject) => {
		uni.request({
			url: requestUrl,
			data: method.toUpperCase() === 'GET' ? undefined : params,
			method: method,
			header,
			success(res) {
				console.log('API响应:', res);
				
				if (res.statusCode !== 200) {
					uni.showToast({
						title: '网络错误',
						duration: 2000,
						icon: 'none'
					});
					reject(new Error(`HTTP ${res.statusCode}`));
					return;
				}

				// 处理业务逻辑错误
				if (res.data && res.data.code && res.data.code !== 200) {
					uni.showToast({
						title: res.data.message || '请求失败',
						duration: 2000,
						icon: 'none'
					});
					reject(new Error(res.data.message || '请求失败'));
					return;
				}

				resolve(res.data);
			},
			fail(err) {
				console.error('请求失败:', err);
				uni.showToast({
					title: '网络连接失败',
					duration: 2000,
					icon: 'none'
				});
				reject(err);
			}
		});
	});
};

// 兼容旧版本的API方法
API.getJson = (route, params, method) => {
	return API.request(route, params, method || 'POST');
};

// GET请求
API.get = (route, params = {}) => {
	return API.request(route, params, 'GET');
};

// POST请求
API.post = (route, params = {}) => {
	return API.request(route, params, 'POST');
};

// PUT请求
API.put = (route, params = {}) => {
	return API.request(route, params, 'PUT');
};

// DELETE请求
API.delete = (route, params = {}) => {
	return API.request(route, params, 'DELETE');
};

// 表单提交请求
API.formPost = (route, params = {}) => {
	return API.request(route, params, 'POST', {
		contentType: 'application/x-www-form-urlencoded'
	});
};

// 表单提交PUT请求
API.formPut = (route, params = {}) => {
	return API.request(route, params, 'PUT', {
		contentType: 'application/x-www-form-urlencoded'
	});
};
API.getUpload = (route, files, params) => {
	const timestamp = SignatureUtils.generateTimestamp();
	const authorization = SignatureUtils.getAuthorization();
	const tenantId = SignatureUtils.getTenantId();
	const secretKey = SignatureUtils.getSecretKey();
	
	let url = CONFIG.host + route;
	
	// 生成签名
	const firstSign = SignatureUtils.generateFirstSignature(
		route,
		timestamp,
		params,
		'',
		secretKey
	);
	
	const finalSign = SignatureUtils.generateFinalSignature(
		tenantId,
		firstSign,
		timestamp,
		authorization
	);
	
	// 将签名参数添加到URL上
	const signatureParams = {
		sign: finalSign,
		timespan: timestamp,
		tenantId: tenantId
	};
	
	const signatureQueryString = SignatureUtils.sortParams(signatureParams);
	if (signatureQueryString) {
		url += (url.includes('?') ? '&' : '?') + signatureQueryString;
	}
	
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: url,
			filePath: files,
			formData: params,
			name: 'file',
			header: {
				'Authorization': authorization
			},
			success: (res) => {
				if (res.statusCode != 200) {
					uni.showToast({
						title: '网络错误',
						duration: 2000
					});
					return false;
				}
				resolve(JSON.parse(res.data))
			}
		});
	});
}
//获取微信支付参数
API.getPayParams = (params) => {
	uni.showLoading({
		title: '加载中',
		mask: true
	});
	
	const timestamp = SignatureUtils.generateTimestamp();
	const authorization = SignatureUtils.getAuthorization();
	const tenantId = SignatureUtils.getTenantId();
	const secretKey = SignatureUtils.getSecretKey();
	
	let url = CONFIG.host + CONFIG.url['orders_wxPay'];
	
	// 生成签名
	const firstSign = SignatureUtils.generateFirstSignature(
		CONFIG.url['orders_wxPay'],
		timestamp,
		params,
		'',
		secretKey
	);
	
	const finalSign = SignatureUtils.generateFinalSignature(
		tenantId,
		firstSign,
		timestamp,
		authorization
	);
	
	// 将签名参数添加到URL上
	const signatureParams = {
		sign: finalSign,
		timespan: timestamp,
		tenantId: tenantId
	};
	
	const signatureQueryString = SignatureUtils.sortParams(signatureParams);
	if (signatureQueryString) {
		url += (url.includes('?') ? '&' : '?') + signatureQueryString;
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: params,
			dataType: "json",
			method: "GET",
			header: {
				'Authorization': authorization
			},
			success(res) {
				uni.hideLoading();
				if (res.statusCode != 200) {
					uni.showToast({
						title: '网络错误',
						duration: 2000
					});
					return false;
				}
				resolve(res.data)
			},
			fail(res) {
				uni.hideLoading();
				console.log(`request调用失败`);
			}
		});
	});
}
//微信支付
API.wx_pay = function(data) {
	return new Promise((resolve, reject) => {
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: String(data.timeStamp),
			nonceStr: data.nonceStr,
			package: data.package,
			signType: data.signType,
			paySign: data.paySign,
			success: function(res) {
				resolve(res);
				console.log('success:' + JSON.stringify(res));
			},
			cancel: function(res) {
				uni.showToast({
					title: '已取消支付',
					icon: 'none'
				})
				reject(res);
			},
			fail: function(err) {
				reject(err);
				console.log('fail:' + JSON.stringify(err));
			}
		});

	})
}

export default API;